﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ManagementTools
{
    public partial class FrmInitialApplicationTables : Form
    {
        public FrmInitialApplicationTables()
        {
            InitializeComponent();
        }

        private void InitMagicApplication_Load(object sender, EventArgs e)
        {
            lstEcho.Items.Add("Magic.Admin没有提供生成数据库的功能");
            lstEcho.Items.Add("本程序通过加载程序集来初始化数据库");
            lstEcho.Items.Add("系统的业务实体一般放在Magic.Application/Entity下");
            lstEcho.Items.Add("代码生成器使用步骤：");
            lstEcho.Items.Add("1. 编写业务功能实体类");
            lstEcho.Items.Add("2. 使用本程序初始化数据表");
            lstEcho.Items.Add("3. 用管理员登录系统，使用代码生成器生成服务和前台代码");
            lstEcho.Items.Add("");
            lstEcho.Items.Add("将在系统数据下生成实体的对应表");

        }
        Assembly mAssembly = null;
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog()
            {
                Filter = "动态链接库(*.DLL)|*.DLL|全部文件(*.*)|*.*",
                RestoreDirectory = true,
                InitialDirectory = Environment.CurrentDirectory,
                FileName= "Magic.Application.dll"
            };
            if(fd.ShowDialog() == DialogResult.OK)
            {
                mAssembly = Assembly.LoadFrom(fd.FileName);
                foreach (var item in mAssembly.GetTypes().Where(it=>it.Namespace.EndsWith("Entity")))
                {
                    clistEntities.Items.Add(item.FullName);
                }

            }
        }

        private void btnInitialDB_Click(object sender, EventArgs e)
        {
            if (clistEntities.CheckedItems.Count<=0) 
            {
                MessageBox.Show("请先选定要初始化的实体","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return; 
            }
           
            try
            {
                foreach (string name in clistEntities.CheckedItems)
                {
                    var types = mAssembly.GetTypes();
                    Type? type = types.FirstOrDefault(t => t.FullName == name);
                    if (type != null)
                    {
                        try
                        {
                            InitialDB( type);
                            lstEcho.Items.Add($"成功初始化{name}");
                        }
                        catch (Exception ex)
                        {
                            lstEcho.Items.Add($"初始化{name}失败");
                            MessageBox.Show(ex.Message, "初始化失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        lstEcho.Items.Add($"未找到{name}实体类定义");
                    }
                }
                MessageBox.Show("初始化成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "初始化失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitialDB( params Type[] entityTypes)
        {
           
            foreach (var type in entityTypes)
            {
                string tableName = type.Name;
                var st = type.GetCustomAttribute<SugarTable>();
                if (st != null && !string.IsNullOrEmpty(st.TableName)) tableName = st.TableName;
                if (App.SugarClient.DbMaintenance.IsAnyTable(tableName))
                {
                    lstEcho.Items.Add($"Table {tableName} Exist. ");
                    if (!App.SugarClient.DbMaintenance.DropTable(tableName))
                    {
                        lstEcho.Items.Add($"Drop table {tableName} Fail!");
                    }
                    else
                    {
                        lstEcho.Items.Add($"Drop table {tableName} Success!");
                    }
                }

                App.SugarClient.CodeFirst.SetStringDefaultLength(200).InitTables(type);//这样一个表就能成功创建了
            }
        }

        private void cmnClear_Click(object sender, EventArgs e)
        {
            lstEcho.Items.Clear();
        }

        private void docxTestToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void dicToEnumToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

    }
}
